<template>
  <el-dialog append-to-body :title="title" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" :visible.sync="visible" :width="'560px'">
    <el-form label-width="120px" size="small" :model="myForm" @submit.native.prevent v-loading="loading">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="权限组名称" required>
            <el-input size="small" v-model.trim="myForm.roleName" placeholder="请输入权限组名称" maxlength="20" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="权限描述">
            <el-input size="small" type="textarea" :rows="2" v-model.trim="myForm.roleDesc" placeholder="请输入权限描述" maxlength="150" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="权限组类型">
            <el-radio-group v-model="myForm.roleType" @change="clearMenu()">
              <el-radio label="0">平台</el-radio>
              <el-radio label="1">商户</el-radio>
              <el-radio label="2">店铺</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="权限">
            <span class="text-brand pointer" @click="openPowerModal()">配置权限</span>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-show="myForm.roleType == '0'">
          <el-form-item label="授权一级部门" required>
            <el-select size="small" v-model="myForm.depart" filterable clearable multiple placeholder="请选择授权一级部门" class="full-width" :disabled="!!permissionId">
              <el-option v-for="item in treeData" :key="item.value" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="submitLoading" @click="closeModal()">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="validForm()">保存</el-button>
    </div>

    <config-component :visible.sync="isShowModel" :name="myForm.roleName" :checked="checkMenuIds" :type="myForm.roleType" @check="getChceked"></config-component>
  </el-dialog>
</template>

<script>
import ConfigComponent from './config';
import { GetDepartmentDataList, AddRole, GetRoleById, UpdateRole } from '@/views/user-management/services/index';
export default {
  props: ['visible', 'title', 'permissionId'],
  components: {
    ConfigComponent
  },
  data() {
    return {
      myForm: {
        roleName: '',
        roleKey: 'system',
        roleDesc: '',
        roleType: '0',
        menus: [],
        depart: []
      },
      halfCheckIds: [],
      treeData: [],
      checkMenuIds: [],
      isShowModel: false,
      loading: false,
      submitLoading: false
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(newValue, oldValue) {
        if (!newValue || !this.permissionId) return;
        this.setForm();
      }
    }
  },
  created() {
    this.getDepartData();
  },
  methods: {
    clearMenu() {
      this.myForm.menus = [];
      this.checkMenuIds = [];
    },
    getChceked(value) {
      this.myForm.menus = value.allCheck.map(item => item.id);
      this.halfCheckIds = value.halfCheck.map(item => item.id);
    },
    openPowerModal() {
      this.checkMenuIds = this.myForm.menus;
      this.isShowModel = true;
    },
    closeModal() {
      this.$emit('update:visible', false);
      this.resetForm();
    },
    validForm() {
      if (!this.myForm.roleName) {
        this.$message.warning('请输入权限组名称!');
        return;
      }
      if (this.myForm.roleType == '0' && (!this.myForm.depart || !this.myForm.depart.length)) {
        this.$message.warning('请选择授权一级部门!');
        return;
      }
      this.submitLoading = true;
      const queryData = {
        proId: 4,
        type: this.myForm.roleType,
        roleName: this.myForm.roleName,
        roleKey: this.myForm.roleKey,
        remark: this.myForm.roleDesc,
        depIds: this.myForm.depart,
        menuIds: this.myForm.menus.concat(this.halfCheckIds)
      }
      if (!this.permissionId) {
        AddRole(queryData)
          .then(success => {
            this.submitLoading = false;
            if (success.code == 200) {
              this.$message.success(`${this.title}成功!`);
              this.closeModal();
              this.$emit('update', true);
            } else {
              this.$message.error(`${this.title}失败!`);
            }
          })
          .catch(error => {
            this.submitLoading = false;
            this.$message.error(error);
          })
      } else {
        UpdateRole({
          ...queryData,
          id: this.permissionId
        })
          .then(success => {
            this.submitLoading = false;
            if (success.code == 200) {
              this.$message.success(`${this.title}成功!`);
              this.closeModal();
              this.$emit('update', true);
            } else {
              this.$message.error(`${this.title}失败!`);
            }
          })
          .catch(error => {
            this.submitLoading = false;
            this.$message.error(error);
          })
      }
    },
    resetForm() {
      this.myForm.roleName = '';
      this.myForm.roleKey = 'system';
      this.myForm.roleDesc = '';
      this.myForm.roleType = '0';
      this.myForm.menus = [];
      this.myForm.depart = [];
    },
    setForm() {
      this.loading = true;
      GetRoleById({ id: this.permissionId })
        .finally(() => (this.loading = false))
        .then(data => {
          if (data.code == 200) {
            this.myForm.roleName = data.data.roleName;
            this.myForm.roleKey = data.data.roleKey;
            this.myForm.roleDesc = data.data.remark;
            this.myForm.roleType = data.data.type.toString();
            this.myForm.menus = data.data.menuIds;
            this.myForm.depart = data.data.depIds;
          }
        })
    },
    getDepartData() {
      GetDepartmentDataList({
        proId: 4,
        depId: '0',
        // isEnable: 1, // 0禁用1启用
        parentId: '0' // 只需要一级父类时传0  只获取顶级权限一层 对应depid需要传0
      })
      .then(res => {
        if (res.code == 200) {
          this.treeData = res.data;
        }
      })
    },
    // 深层递归返回选中的父级id
    deepTreeData(id, list) {
      let nodes = [];
      let myDeep = (parentId, childlist) => {
        if (!childlist || !childlist.length) return;
        childlist.forEach(child => {
          if (child.id == parentId) {
            nodes.unshift(child);
            myDeep(child.parentId, list);
          } else {
            if (child.children && child.children.length) {
              myDeep(parentId, child.children);
            }
          }
        })
      }

      myDeep(id, list);
      return nodes;
    }
  }
}
</script>

<style lang="scss" scoped>
.tag_item {
  margin-right: 5px;
}
</style>
